<template>
  <div class="page-content">
    <el-card shadow="never">
      <el-form
        ref="form"
        label-width="7em"
        :model="formData"
        :rules="rules"
      >
        <el-row :gutter="24">
          <el-col :span="24">
            <h3>关联销售单</h3>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联订单号：">
              <el-input style="max-width: 400px; margin-right: 15px" v-model="formData.relateOrderIds" placeholder="多个订单号之间以英文逗号分隔"></el-input>
              <span class="red">提示：多个订单号之前以英文逗号分隔</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <h3>收货人信息</h3>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="收货人"
              prop="consigneeName"
            >
              <el-input v-model.trim="formData.consigneeName" placeholder="请输入收货人"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="收货人电话"
              prop="consigneeMobile"
            >
              <el-input v-model.trim="formData.consigneeMobile" type="tel" placeholder="请输入收货人电话"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="收货地址"
              prop="consigneeDetailAddress"
            >
              <el-cascader
                v-if="!loading"
                ref="city"
                v-model="city"
                style="width: 100%"
                :props="regionProps"
                @change="onChangeRegion">
              </el-cascader>
              <el-input
                type="textarea"
                style="margin-top: 10px"
                placeholder="详细地址，街道，门牌等"
                v-model.trim="formData.consigneeDetailAddress"
                :rows="3"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <h3>供应商信息</h3>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="公司名称"
              prop="supplierCompanyName"
            >
              <el-input v-model.trim="formData.supplierCompanyName" placeholder="请输入公司名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="联系电话"
              prop="supplierMobile"
            >
              <el-input v-model.trim="formData.supplierMobile" type="tel" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="发货状态"
              prop="deliveryState"
            >
              <el-select v-model="formData.deliveryState" placeholder="请选择">
                <el-option
                  v-for="(label, value) of deliveryStateMap"
                  :key="value"
                  :value="value"
                  :label="label"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <h3>
              商品信息
              <!-- <div class="add-item"> -->
              <el-button type="primary" plain size="small" icon="el-icon-download" @click="onDownloadImportTemplate">下载导入模版</el-button>
              <el-upload
                style="display: inline-block; margin: 0 10px"
                name="file"
                action=""
                accept=".xls,.xlsx"
                :http-request="onImportItem"
                :show-file-list="false">
                <el-button :loading="importItemLoading" type="primary" plain size="small" icon="el-icon-upload2">批量导入商品</el-button>
              </el-upload>
              <el-button type="primary" plain size="small" icon="el-icon-edit" @click="addItem()">自行填写</el-button>
              <el-button type="primary" plain size="small" icon="el-icon-plus" @click="$refs.goodsSelect.open()">添加采购库商品</el-button>
              <!-- </div> -->
            </h3>
          </el-col>

          <el-col :span="24">
            <el-table class="table" :data="formData.orderItems" border empty-text="请添加商品">
              <el-table-column label="添加类型" width="120px" align="center">
                <template slot-scope="{ row }">
                  {{row.type === 1 ? '采购库添加' : '自行填写'}}
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>商品类目
                </div>
                <template slot-scope="{ row, $index }">
                  <template v-if="row.type === 1">
                    {{row.categoryNames ? row.categoryNames.join(',') : '-'}}
                  </template>
                  <el-form-item
                    v-else
                    label-width="0"
                    :prop="`orderItems.${$index}.cids`"
                    :rules="{required: true, message: '请选择商品类目', type: 'array'}"
                  >
                    <el-cascader
                      v-model="row.cids"
                      style="width: 100%"
                      size="mini"
                      :options="categoryList"
                      :props="categoryProps"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>商品名称
                </div>
                <template slot-scope="{ row, $index }">
                  <template v-if="row.type === 1">
                    {{row.name}}
                  </template>
                  <el-form-item
                    v-else
                    label-width="0"
                    :prop="`orderItems.${$index}.name`"
                    :rules="{required: true, message: '请输入商品名称'}"
                  >
                    <el-input
                      size="mini"
                      v-model.trim="row.name"
                      placeholder="请输入商品名称"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>品牌
                </div>
                <template slot-scope="{ row, $index }">
                  <template v-if="row.type === 1">
                    {{row.brand}}
                  </template>
                  <el-form-item
                    v-else
                    label-width="0"
                    :prop="`orderItems.${$index}.brand`"
                    :rules="{required: true, message: '请输入品牌'}"
                  >
                    <el-input
                      size="mini"
                      v-model.trim="row.brand"
                      placeholder="请输入品牌"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>规格型号
                </div>
                <template slot-scope="{ row, $index }">
                  <template v-if="row.type === 1">
                    {{row.attribute}}
                  </template>
                  <el-form-item
                    v-else
                    label-width="0"
                    :prop="`orderItems.${$index}.attribute`"
                    :rules="{required: true, message: '请输入规格型号'}"
                  >
                    <el-input
                      size="mini"
                      v-model.trim="row.attribute"
                      placeholder="请输入规格型号"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column align="center" label="商品图片">
                <template slot-scope="{ row, $index }">
                  <el-image
                    v-if="row.picUrl"
                    class="item-img"
                    :src="row.picUrl"
                    :preview-src-list="[row.picUrl]">
                  </el-image>

                  <template v-if="row.type === 2">
                    <el-form-item
                      label-width="0"
                      :prop="`orderItems.${$index}.picUrl`"
                    >
                      <el-upload
                        name="file"
                        action=""
                        accept="image/*"
                        :http-request="($event) => uploadGoodsImage($event, row)"
                        :show-file-list="false">
                        <el-button size="mini" icon="el-icon-upload2">{{row.picUrl ? '替换图片' : '上传图片'}}</el-button>
                      </el-upload>
                    </el-form-item>
                  </template>
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>数量
                </div>
                <template slot-scope="{ row }">
                  <el-input-number
                    v-model="row.num"
                    size="mini"
                    :min="1"
                  ></el-input-number>
                </template>
              </el-table-column>

              <el-table-column align="center">
                <div slot="header">
                  <span class="red">*</span>单价（元）
                </div>
                <template slot-scope="{ row }">
                  <el-input-number
                    v-model="row.price"
                    size="mini"
                    :min=".01"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>

              <el-table-column label="采购合同" align="center">
                <template slot-scope="{ row }">
                  <el-upload
                    name="file"
                    action=""
                    :show-file-list="false"
                    :http-request="$event => onUploadContract($event, row)"
                  >
                    <el-button type="text">{{row.contractUrl ? '重新上传' : '上传'}}</el-button>
                  </el-upload>
                </template>
              </el-table-column>

              <el-table-column align="center" label="参考价（元）">
                <template slot-scope="{ row }">
                  {{row.referencePrice ? $util.formatAmount(row.referencePrice) : '-'}}
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作">
                <template slot-scope="{ row }">
                  <el-popconfirm title="确认删除？" @confirm="onDeleteItem(row)">
                    <el-button type="text" slot="reference">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>

            </el-table>

          </el-col>

          <el-col :span="24" class="footer">
            <div class="price">
              订单总金额：<strong class="red">{{totalPrice}}</strong>元
            </div>
            <div>
              <el-button @click="$router.back()">取 消</el-button>
              <el-button type="primary" @click="onSubmit">提 交</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <GoodsSelect ref="goodsSelect" @confirm="onGoodsSelected"></GoodsSelect>
  </div>
</template>

<script>
import { region } from '@/api/common';
import { categoryList } from '@/api/category';
import { importParsing, uploadGoodsImage } from '@/api/purchase/goods';
import { add, update, detail, uploadContract } from '@/api/purchase/offlineOrder';
import { deliveryStateMap } from '@/config/purchase/offline';
import { omit, add as numberAdd, multiply } from 'lodash';
import GoodsSelect from '../../../components/GoodsSelect.vue';

function getFormData (data = {}) {
  return {
    consigneeName: '',
    consigneeMobile: '',
    consigneeProvinceId: '',
    provinceName: '',
    consigneeCityId: '',
    cityName: '',
    consigneeCountyId: '',
    countyName: '',
    consigneeDetailAddress: '',
    supplierCompanyName: '',
    supplierMobile: '',
    // deliveryState: '',
    orderItems: [],
    ...data,
    deliveryState: data.deliveryState ? data.deliveryState.toString() : '',
  };
}

function getItemData (type, item = {}) {
  return {
    type,
    cids: null,
    cidLev1: '',
    cidLev2: '',
    cidLev3: '',
    source: 1,
    name: '',
    brand: '',
    attribute: '',
    referencePrice: '',
    price: 1,
    picUrl: '',
    num: 1,
    contractUrl: '',
    ...item,
  };
}

export default {
  name: 'create',

  components: { GoodsSelect },

  data () {
    const checkAddress = (rule, value, callback) => {
      if (this.city.length !== 3) {
        callback(new Error('请选择城市'));
      } else {
        callback();
      }
    };
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'));
      } else if (!/^[0-9-]+$/.test(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      formData: getFormData(),
      city: [],
      cityMap: {},
      rules: {
        consigneeName: [{ required: true, message: '请输入收货人' }],
        consigneeMobile: [
          { required: true, message: '请输入收货电话' },
          { validator: checkMobile, trigger: 'blur' },
        ],
        consigneeDetailAddress: [
          { required: true, message: '请选择并输入详细地址' },
          { validator: checkAddress },
        ],
        supplierCompanyName: [{ required: true, message: '请输入公司名称' }],
        supplierMobile: [
          { required: true, message: '请输入联系电话' },
          { validator: checkMobile, trigger: 'blur' },
        ],
        deliveryState: [{ required: true, message: '请选择发货状态' }],
      },
      regionProps: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          this.getRegion(node.value || 0, node.level === 2).then(resolve);
        },
      },
      categoryProps: {
        value: 'id',
        label: 'name',
        children: 'children',
      },
      categoryList: [],
      deliveryStateMap,

      importItemLoading: false,
    };
  },

  async created () {
    this.getCategoryList();
    if (!this.isAdd) {
      await this.getDetail();
    }
    this.loading = false;
  },

  computed: {
    isAdd () {
      return this.$route.meta.isAdd;
    },

    totalPrice () {
      let totalPrice = 0;
      this.formData.orderItems.forEach(item => {
        totalPrice = numberAdd(totalPrice, multiply(item.price, item.num));
      });
      return this.$util.formatAmount(totalPrice);
    },
  },

  methods: {
    async getDetail () {
      const info = await detail(this.$route.params.id);

      this.formData = getFormData(omit(info, ['orderItems']));
      this.city = [
        this.formData.consigneeProvinceId.toString(),
        this.formData.consigneeCityId.toString(),
        this.formData.consigneeCountyId.toString(),
      ];

      info.orderItems.forEach(item => {
        if (item.type === 2) {
          item.cids = [item.cidLev1, item.cidLev2, item.cidLev3];
        }
        this.addItem(item, item.type);
      });
    },

    addItem (item = {}, type = 2) {
      this.formData.orderItems.push(getItemData(type, item));
    },

    async getCategoryList () {
      this.categoryList = await categoryList();
    },

    async getRegion (parent = 0, leaf = false) {
      const list = await region(parent);
      return list.map(item => {
        this.cityMap[item.code] = item;
        return {
          value: item.code,
          label: item.name,
          leaf: leaf,
        };
      });
    },

    onChangeRegion ($event) {
      // console.log($event, arguments);
      this.formData.consigneeProvinceId = $event[0];
      this.formData.consigneeCityId = $event[1];
      this.formData.consigneeCountyId = $event[2];
    },

    async onImportItem (param) {
      this.importItemLoading = true;
      try {
        const result = await importParsing(param.file);
        result.forEach(item => {
          this.addItem(item);
        });
        this.$message.success(`共导入${result.length}商品`);
      } catch (error) {
        console.error(error);
      }
      this.importItemLoading = false;
    },

    async uploadGoodsImage (param, row) {
      try {
        const result = await uploadGoodsImage(param.file);
        console.log('result', result);
        row.picUrl = result;
      } catch (error) {
        console.error(error);
      }
    },

    onGoodsSelected (selected) {
      selected.forEach(item => {
        this.addItem(item, 1);
      });
    },

    async onDeleteItem (row) {
      const index = this.formData.orderItems.indexOf(row);
      if (index > -1) {
        this.formData.orderItems.splice(index, 1);
      }
    },

    onDownloadImportTemplate () {
      this.$util.downloadFile('https://oss.tlwok.com/%E9%87%87%E8%B4%AD%E5%B9%B3%E5%8F%B0%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5.xlsx');
    },

    async onUploadContract (param, row) {
      const loading = this.$loading();
      try {
        row.contractUrl = await uploadContract(param.file);
        this.$message.success('上传成功');
      } catch (error) {
        console.error(error);
      }
      loading.close();
    },

    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.formData.orderItems.length) {
            this.$message.error('请添加商品');
            return false;
          }
          const cityMap = this.cityMap;
          this.formData.provinceName = cityMap[this.city[0]].name;
          this.formData.cityName = cityMap[this.city[1]].name;
          this.formData.countyName = cityMap[this.city[2]].name;

          const formData = omit(this.formData, ['orderItems']);
          formData.orderItems = this.formData.orderItems.map(item => {
            const orderItem = omit(item, ['cids', 'categoryNames']);
            if (item.type === 2) {
              orderItem.cidLev1 = item.cids[0];
              orderItem.cidLev2 = item.cids[1];
              orderItem.cidLev3 = item.cids[2];
            }
            return orderItem;
          });
          const loading = this.$loading();
          try {
            const submitFun = this.isAdd ? add : update;
            await submitFun(formData);
            loading.close();
            this.$message.success(this.isAdd ? '添加成功' : '编辑成功');
            this.$router.back();
          } catch (error) {
            console.error(error);
            loading.close();
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">

.red {
  color: red;
}

.add-item {
  text-align: center;
  margin-top: 20px;
}

.item-img {
  width: 50px;
  max-height: 50px;
}

.footer {
  text-align: center;
  margin: 40px 0;
  .price {
    margin-bottom: 20px;
  }
  button {
    margin: 0 20px;
    width: 120px;
  }
}

.table .el-form-item {
  margin-bottom: 0;
  ::v-deep {
    .el-form-item__error {
      position: relative;
      text-align: center;
      padding: 0;
      white-space: initial;
    }
  }
}
</style>
